//app.js
import Https from "./utils/api"
import Websocket from "./utils/socket"
var talk = []
const http = new Https
var QQMapWX = require('./utils/qqmap-wx-jssdk')
App({
  onLaunch: function () {
    this.socketInit()
    wx.login({
      success(res) {
        // 换取openId  然后换取获取token
        http.request('wx/login', { code: res.code }, "POST").then((res)=>{
          wx.setStorageSync('token', res.data)
        })
      }
    })
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        wx.setStorageSync('latitude', res.latitude)
        wx.setStorageSync('longitude', res.longitude)
        http.request('user/local', {
          latitude: res.latitude,
          longitude: res.longitude
        }).then(res => {
          console.log(res)
          var address = res.data.result.formatted_address
          http.request('city/province',{
            address:address
          }).then(res=>{
                wx.setStorageSync('province', res.data.id)
          })
        })
      }
    })
  },
  onShow() {
    this.linkWebsocket()
  },
  // 建立连接
  linkWebsocket() {
    this.websocket.initWebSocket({
      url: this.globalData.websocketUrl,
      success(res) {
        // console.log(res)
      },
      fail(err) {
        console.log("linkWebsocket err", err)
      }
    })
  },
  /**
   * 创建websocket对象
   */
  socketInit() {
    // 创建websocket对象
    this.websocket = new Websocket({
      // true代表启用心跳检测和断线重连
      heartCheck: false,
      isReconnection: true
    });

    // 监听websocket状态
    this.websocket.onSocketClosed({
      url: this.globalData.websocketUrl,
      success(res) {
        console.log(res)
      },
      fail(err) {
        console.log("onSocketClosed err", err)
      }
    })
    // 监听网络变化
    this.websocket.onNetworkChange({
      url: this.globalData.websocketUrl,
      success(res) {
        console.log(res)
      },
      fail(err) {
        console.log("onNetworkChange err", err)
      }
    })

    // 监听服务器返回
    this.websocket.onReceivedMsg(result => {
      console.log('app.js收到服务器内容：' + result.data);
      // 要进行的操作
      var data = JSON.parse(result.data)
      let array = wx.getStorageSync(`${data.send_id}to${data.rec_id}`) || []
      array.push(data)
      talk.push(data)
      wx.setStorageSync('num', talk.length)
      wx.setStorageSync(data.send_id + "to" + data.rec_id, array)
    })

  },

  // 向其他页面暴露当前websocket连接
  getSocket() {
    return this.websocket;
  },
  globalData: {
    userInfo: null,
    websocketUrl: "ws://47.101.202.80:9502",
    qqmapsdk: new QQMapWX({
      key: 'UBSBZ-QXQL3-5V63Z-YHR2C-D2M5T-EIFOT' // 必填
    })
  }
})